#include "timer.h"
#include "Delay.h"

static uint16_t flag;
static uint16_t Num;

void TIM_Init()
{
    GPIO_InitTypeDef GPIO_InitStruct;
    TIM_TimeBaseInitTypeDef TIM_BaseInitStruct;
    TIM_OCInitTypeDef TIM_OCInitStruct;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);

    GPIO_InitStruct.GPIO_Mode  = GPIO_Mode_AF_PP;
    GPIO_InitStruct.GPIO_Pin   = GPIO_Pin_2;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA,&GPIO_InitStruct);

    TIM_InternalClockConfig(TIM2);

    /*时基设置*/
    TIM_BaseInitStruct.TIM_ClockDivision     = TIM_CKD_DIV1;         /*时钟分割*/
    TIM_BaseInitStruct.TIM_CounterMode       = TIM_CounterMode_Up;   /*上升沿触发*/
    TIM_BaseInitStruct.TIM_Period            = 20000 - 1;   /*自动重载*/
    TIM_BaseInitStruct.TIM_Prescaler         = 72 - 1;      /*预分频*/
    TIM_BaseInitStruct.TIM_RepetitionCounter = 0;        /*定时器结束后0+1次进入中断*/
    TIM_TimeBaseInit(TIM2,&TIM_BaseInitStruct);

    /*比较输出*/
    TIM_OCStructInit(&TIM_OCInitStruct);
    TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStruct.TIM_OCNPolarity = TIM_OCNPolarity_High;
    TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStruct.TIM_Pulse = 50;
    TIM_OC3Init(TIM2,&TIM_OCInitStruct);

    TIM_Cmd(TIM2,ENABLE);
}

/*占空比设置*/
void PWM_SetCompare3(uint16_t value)
{
    TIM_SetCompare3(TIM2,value);
}

void LED_PWM_Control_Step1_Up(void)
{    
   PWM_SetCompare3(Num);
          if(flag == 0)
          {
           Num += 500;
          }
          if(Num > 10000)
          {
           flag = 1;
           Delay_ms(700);
          }
          if(flag == 1)
          {
           Num -= 500;
          }
          if(Num < 10 )
          {
           flag = 0;
           Delay_ms(700);
          }
          Delay_ms(1); 
}

void LED_PWM_Control_Step2_Up(void)
{
    PWM_SetCompare3(Num);
          if(flag == 0)
          {
           Num += 500;
          }
          if(Num > 14000)
          {
           flag = 1;
           Delay_ms(400);
          }
          if(flag == 1)
          {
           Num -= 500;
          }
          if(Num < 10 )
          {
           flag = 0;
           Delay_ms(400);
          }
          Delay_us(800); 
}
void LED_PWM_Control_Step3_Up(void)
{
    PWM_SetCompare3(Num);
          if(flag == 0)
          {
           Num += 500;
          }
          if(Num > 14000)
          {
           flag = 1;
           Delay_ms(100);
          }
          if(flag == 1)
          {
           Num -= 500;
          }
          if(Num < 10 )
          {
           flag = 0;
           Delay_ms(100);
          }
          Delay_us(150); 
}

